<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                           |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Activity;

use AuctionCore\Common\PhpRedis;

/**
 * 车来车往开奖活动
 *
 * @author Xmh
 */
class Lottory
{

    private $lottoryModel;
    private $lottoryTicketModel;
    private $myLottoryModel;

    public function __construct()
    {
        $this->lottoryModel = M('lottory', 'clcw_', 'DB_CLCW');
        $this->lottoryTicketModel = M('lottory_ticket', 'clcw_', 'DB_CLCW');
        $this->myLottoryModel = M('my_lottory', 'clcw_', 'DB_CLCW');
    }

    /**
     * 获取当前是否有活动，有则返回活动ID，无则返回0
     */
    public function is_lottory_online()
    {
        $condition['lottory_status'] = 2;
        $condition['lottory_type'] = 1;
        $condition['lottory_start_time'] = ['elt', date("Y-m-d H:i:s")];
        $condition['lottory_end_time'] = ['egt', date("Y-m-d H:i:s")];
        $lotteryList = $this->lottoryModel->where($condition)->select();
        if (!empty($lotteryList)) {
            return $lotteryList;
        } else {
            $lotId = 0;
        }
        return $lotId;
    }

    /**
     * 发送抽奖券
     *
     * @param $uid
     * @param $inCode
     *
     * @return boolean
     */
    public function send_lottery_ticket($uid, $inCode)
    {
        $lotteryList = $this->isLottoryOnline();

        if (empty($lotteryList)) {
            return false;
        }
        foreach ($lotteryList as $item){
            $redis = new \AuctionCore\Common\PhpRedis(0);

            $keyName = getRedisKeyByCode('REDIS_KEY','100012');
            $res = $redis->rPush($keyName, json_encode([
                'uid' => $uid,
                'lot_id' => $item['id'],
                'invite_code' => $inCode]

            ));
        }
        return $res;
    }

    /**
     * 执行开奖操作
     *
     * @param int   $lotId
     * @param float $sse
     * @param float $szs
     * @param int   $lottoryWinNum
     *
     * @return bool
     */
    public function doRunLottory($lotId, $sse, $szs, $lottoryWinNum)
    {
        if ($lotId < 1) {
            return false;
        }
        $data['id'] = $lotId;
        $data['sse'] = $sse;
        $data['szs'] = $szs;
        $data['lottory_win_num'] = $lottoryWinNum;
        M()->startTrans();
        $res1 = $this->lottoryModel->save($data);

        $ticket['lot_id'] = ['eq', $lotId];
        $ticket['lottory_ticket_num'] = ['eq', $lottoryWinNum];
        $res2 = $this->lottoryTicketModel->where($ticket)->setField('lottory_ticket_status', '1');

        $ticketMap['lot_id'] = ['eq', $lotId];
        $ticketMap['lottory_ticket_num'] = ['neq', $lottoryWinNum];
        $res3 = $this->lottoryTicketModel->where($ticketMap)->setField('lottory_ticket_status', '2');

        $win_uid = $this->lottoryTicketModel->where($ticket)->getField('uid');
        $myLottory['lot_id'] = ['eq', $lotId];
        $myLottory['uid'] = ['eq', $win_uid];
        $res4 = $this->myLottoryModel->where($myLottory)->setField('lot_status', 1);

        $myLottory_map['lot_id'] = ['eq', $lotId];
        $myLottory_map['uid'] = ['neq', $win_uid];
        $res5 = $this->myLottoryModel->where($myLottory_map)->setField('lot_status', 2);
        if ($res1 !== false && $res2 !== false && $res3 !== false &&
            $res4 !== false && $res5 !== false
        ) {
            M()->commit();
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

    /**
     * 获取开奖活动列表
     *
     * @param int   $page
     * @param int   $pageSize
     * @param array $params
     *
     * @return array
     */
    public static function getLottoryList($page, $pageSize, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $pageSize = $pageSize < 1 ? 10 : (int)$pageSize;
        $map = [];
        /**
         * 搜索条件：1、活动ID 2、名称 3、类型 4、状态 5、开始时间 6、结束时间
         */
        if ($params['lot_id']) {
            $map['l.id'] = ['eq', $params['lot_id']];
        }
        if ($params['lot_name']) {
            $map['l.lottory_name'] = ['LIKE', '%' . $params['lot_name'] . '%'];
        }
        if ($params['lot_type']) {
            $map['l.lottory_type'] = ['eq', $params['lot_type']];
        }
        if ($params['lot_status']) {
            $map['l.lottory_status'] = ['eq', $params['lot_status']];
        }
        if ($params['start_time'] && !$params['end_time']) {
            $where['l.lottory_start_time'] = ['egt', strtotime($params['start_time'] . " 00:00:00")];
            $where['l.lottory_end_time'] = ['egt', strtotime($params['start_time'] . " 00:00:00")];
            $where['_logic'] = "OR";
            $map['_complex'] = $where;
        }
        if ($params['end_time'] && !$params['start_time']) {
            $where['l.lottory_start_time'] = ['elt', strtotime($params['end_time'] . " 23:59:59")];
            $where['l.lottory_end_time'] = ['elt', strtotime($params['end_time'] . " 23:59:59")];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }
        $where = [];
        if ($params['start_time'] && $params['end_time']) {
            $where['l.lottory_start_time'] = [
                ['egt', strtotime($params['start_time'] . " 00:00:00")],
                ['elt', strtotime($params['end_time'] . " 23:59:59")],
                'AND'
            ];
            $where['l.lottory_end_time'] = [
                ['egt', strtotime($params['start_time'] . " 00:00:00")],
                ['elt', strtotime($params['end_time'] . " 23:59:59")],
                'AND'
            ];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }
        //查询历史活动列表 - 进行中和正常结束
        if ($params['his_lottory']) {
            $map['l.lottory_status'] = [['eq', 2], ['eq', 3], 'OR'];
        }
        //已开奖
        if ($params['history_lottory']) {
            $map['l.lottory_status'] = ['eq', 3];
            $map['l.lottory_win_num'] = ['gt', 0];
        }
        $cols = "l.id,l.lottory_name,l.lottory_image,l.lottory_type,l.lottory_award,l.lottory_win_num,
                 l.lottory_start_time,l.lottory_end_time,l.lottory_time,l.lottory_status,l.create_time";
        $order = "l.id DESC";
        $total = M('lottory', 'clcw_', 'DB_CLCW')->alias('l')->where($map)->count();
        $list = M('lottory', 'clcw_', 'DB_CLCW')->alias("l")->field($cols)
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($pageSize)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['lottory_ticket_nums'] = self::getLottoryTicketNum($v['id']);
        }
        $result = [
            'list'  => $list,
            'total' => $total,
        ];
        return $result;
    }

    /**
     * 获得历史活动列表 - 已结束并开奖
     */
    public function get_history_lottory_list($params, $limit = '')
    {
        $map = [];
        if ($params['lottory_status']) {
            $map['l.lottory_status'] = ['eq', $params['lottory_status']];
        }
        $map['l.lottory_win_num'] = ['gt', 0];
        $cols = "l.id,l.lottory_name,l.lottory_image,l.lottory_type,l.lottory_award,l.lottory_win_num,
                 l.lottory_start_time,l.lottory_end_time,l.lottory_time,l.lottory_status,l.create_time";
        $order = "l.id DESC";
        $list = M('lottory', 'clcw_', 'DB_CLCW')->alias("l")->field($cols)
            ->where($map)
            ->limit($limit)
            ->order($order)
            ->select();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['lottory_time'] = date("Y年m月d日", $v['lottory_time']);
                $list[$k]['lottory_cycle'] = date("Y年m月d日", $v['lottory_start_time']) . '-'
                    . date("Y年m月d日", $v['lottory_end_time']);
                $winDetail = $this->get_win_detail($v['id'], $v['lottory_win_num']);
                $info = D('ClcwUser', 'Logic')->getUserInfoByUid($winDetail['uid']);
                $list[$k]['win_user'] = showHideMobile($info['mobile']);
                $list[$k]['lottory_win_num'] = lottory_ticket_format($v['lottory_win_num']);
                $list[$k]['lottory_ticket_nums'] = self::getLottoryTicketNum($v['id']);
            }
        }
        return $list;
    }

    /**
     * 获得开奖活动详情
     *
     * @param int $id
     *
     * @return bool|mixed
     */
    public function getLottoryDetail($id = 0)
    {
        if ($id < 1) {
            return false;
        }
        return $this->lottoryModel->find($id);
    }

    /**
     * 创建开奖活动
     *
     * @param array $data
     *
     * @return int
     */
    public function createLottory($data = [])
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        return $this->lottoryModel->add($data);
    }

    /**
     * 更新开奖活动
     *
     * @param int   $lotId
     * @param array $data
     *
     * @return int
     */
    public function update_lottory($lotId, $data = [])
    {
        if ($lotId < 1) {
            return false;
        }
        return $this->lottoryModel->save($data);
    }

    /**
     * 上下线活动操作
     *
     * @param $lotId
     * @param $lotStatus
     *
     * @return bool
     */
    public function updateLottoryStatus($lotId, $lotStatus)
    {
        $condition['id'] = $lotId;
        $data['lottory_status'] = $lotStatus;
        if ($lotStatus == 2) {
            $total = $this->lottoryModel->where($data)->count();
            if ($total > 0) {
                echo \AuctionCore\Common\Util::auto_jsonp_or_json($_REQUEST, ['code' => 500, 'msg' => '已有活动进行中']);
                exit;
            }
            $now = time();
            $where['lottory_start_time'] = ['lt', $now];
            $where['lottory_end_time'] = ['lt', $now];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
            $map['id'] = $lotId;
            $total_num = $this->lottoryModel->where($map)->count();
            if ($total_num) {
                echo \AuctionCore\Common\Util::auto_jsonp_or_json($_REQUEST, ['code' => 500, 'msg' => '活动开始时间已过期']);
                exit;
            }
        }
        return $this->lottoryModel->where($condition)
            ->setField($data);
    }

    /**
     * 更新活动
     *
     * @param array $data
     *
     * @return bool
     */
    public function saveLottory($data = [])
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        return $this->lottoryModel->save($data);
    }

    /**
     * 创建活动对应的奖券
     *
     * @param array $data
     *
     * @return boolean|int
     */
    public function create_lottory_ticket($data = [])
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }
        $id = $this->lottoryTicketModel->add($data);
        $condition['lot_id'] = $data['lot_id'];
        $condition['id'] = $id;
        $ticket_num = $this->lottoryTicketModel->where($condition)->max('lottory_ticket_num');
        $this->lottoryTicketModel->where($condition)->setField(['lottory_ticket_num' => $ticket_num]);
    }

    /**
     * 获取开奖活动对应的奖券列表
     *
     * @param $page
     * @param $pageSize
     * @param $params
     *
     * @return array
     */
    public static function getLottoryTicketList($page, $pageSize, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $pageSize = $pageSize < 1 ? 10 : (int)$pageSize;
        $map = [];
        /**
         * 搜索条件：
         * 1、奖券ID 2、奖券类型 3、个人ID 4、帐号 5、邀请人ID
         * 6、开奖情况：1、已中奖 2、未中奖 7、开始时间 8、结束时间
         */
        if ($params['lot_id']) {
            $map['lt.lot_id'] = ['eq', $params['lot_id']];
        }
        if ($params['lt_num']) {
            $lt_num = preg_replace('/^0+/', '', trim($params['lt_num']));
            $map['lt.lottory_ticket_num'] = ['LIKE', '%' . $lt_num . '%'];
        }
        if ($params['lt_type']) {
            $map['lt.lottory_ticket_comefrom'] = ['eq', $params['lt_type']];
        }
        if ($params['lt_uid']) {
            $map['lt.uid'] = ['LIKE', '%' . $params['lt_uid'] . '%'];
        }
        if ($params['lt_phone']) {
            $phone = trim($params['lt_phone']);
            $info = D('ClcwUser', 'Logic')->getUserInfoByMobile($phone);
            if (!empty($info)) {
                $map['lt.uid'] = ['eq', $info['uid']];
            } else {
                $map['lt.uid'] = ['eq', 0];
            }
        }
        if ($params['invite_uid']) {
            $map['lt.lottory_ticket_comefrom'] = ['eq', 3];
            $map['lt.invite_uid'] = ['LIKE', '%' . $params['invite_uid'] . '%'];
        }
        if ($params['lt_status']) {
            $lt_status = $params['lt_status'];
            if ($lt_status == 1) {
                $map['lt.lottory_ticket_status'] = ['eq', $params['lt_status']];
            } else {
                $map['lt.lottory_ticket_status'] = ['eq', $params['lt_status']];
            }
        }
        if ($params['start_time']) {
            $map['lt.create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['lt.create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['lt.create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $cols = "l.lottory_win_num,
                 lt.id,lt.lot_id,lt.uid,lt.invite_uid,lt.lottory_ticket_num,lt.lottory_ticket_comefrom,
                 lt.lottory_ticket_status,lt.create_time";
        $order = "lt.id DESC";
        $total = M('lottory_ticket', 'clcw_', 'DB_CLCW')->alias('lt')
            ->where($map)->count();
        $list = M('lottory_ticket', 'clcw_', 'DB_CLCW')->alias('lt')->field($cols)
            ->join('clcw_lottory as l ON lt.lot_id=l.id')
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($pageSize)
            ->select();
        foreach ($list as $k => $v) {
            $info = D('ClcwUser', 'Logic')->getClcwUserInfo($v['uid']);
            $list[$k]['user'] = $info['mobile'];
        }
        $result = [
            'list'  => $list,
            'total' => $total,
        ];
        return $result;
    }

    /**
     * 获取活动的奖券数量
     *
     * @param int $lotId
     *
     * @return bool
     */
    public static function getLottoryTicketNum($lotId = 0)
    {
        if ($lotId < 1) {
            return false;
        }
        $condition['lot_id'] = $lotId;
        return M('lottory_ticket', 'clcw_', 'DB_CLCW')->where($condition)->count();
    }

    /**
     * 获取我的开奖活动列表
     *
     * @param $page
     * @param $pageSize
     * @param $params
     *
     * @return array
     */
    public function my_lottory_list($page, $pageSize, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $pageSize = $pageSize < 1 ? 20 : (int)$pageSize;
        $map = [];
        if ($params['uid']) {
            $map['ml.uid'] = ['eq', $params['uid']];
        }
        $map['l.lottory_status'] = [['eq', 2], ['eq', 3], 'OR'];
        $cols = "ml.lot_status,l.id,l.lottory_name,l.lottory_type,l.lottory_time,l.lottory_status";
        $order = 'l.id DESC';
        $total = M('my_lottory', 'clcw_', 'DB_CLCW')->alias('ml')
            ->join('clcw_lottory as l ON ml.lot_id = l.id')
            ->where($map)
            ->count();
        $list = M('my_lottory', 'clcw_', 'DB_CLCW')->alias('ml')->field($cols)
            ->join('clcw_lottory as l ON ml.lot_id = l.id')
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($pageSize)
            ->select();
        $list = empty($list) ? [] : $list;
//                echo M()->getLastSql();
        $result = [
            'currentpage' => $page,
            'pagesize'    => $pageSize,
            'maxcount'    => $total,
            'maxpage'     => ceil($total / $pageSize),
            'list'        => $list
        ];
        return $result;
    }

    /**
     * 获取我的开奖活动对应的奖券列表
     *
     * @param $params
     *
     * @return array|bool
     */
    public function get_my_lottory_ticket_list($params)
    {
        if (empty($params)) {
            return false;
        }
        $map['lt.uid'] = ['eq', $params['uid']];
        $map['l.id'] = ['eq', $params['lot_id']];
        $cols = "l.id,l.lottory_status,lt.id,lt.lot_id,lt.uid,lt.invite_uid,
                lt.lottory_ticket_num,lt.lottory_ticket_comefrom,
                lt.lottory_ticket_status,lt.create_time";
        $order = "lt.id DESC";
        $total = M('lottory_ticket', 'clcw_', 'DB_CLCW')->alias('lt')
            ->join('clcw_lottory as l ON lt.lot_id = l.id')
            ->where($map)->count();
        $list = M('lottory_ticket', 'clcw_', 'DB_CLCW')->alias('lt')->field($cols)
            ->join('clcw_lottory as l ON lt.lot_id = l.id')
            ->where($map)
            ->order($order)
            ->select();
//        echo M()->getLastSql();
        foreach ($list as $k => $v) {
            $comefrom = $v['lottory_ticket_comefrom'];
            $info = D('ClcwUser', 'Logic')->getUserInfoByUid($v['invite_uid']);
            $list[$k]['user'] = $info['pwd_mobile'];
            if ($comefrom == 1) {
                $ticket_comefrom = '注册成功';
            } elseif ($comefrom == 2) {
                $invite = D('ClcwUser', 'Logic')->getUserInfoByUid($v['invite_uid']);
                if (!empty($invite)) {
                    $ticket_comefrom = showHideMobile($invite['pwd_mobile']) . '注册成功';
                } else {
                    $ticket_comefrom = '邀请注册成功';
                }
            } elseif ($comefrom == 3) {
                $ticket_comefrom = '受邀注册成功';
            }
            $lottory_status = $v['lottory_status'];
            if ($lottory_status == 2) {
                $lottory_status_name = '待开奖';
            } elseif ($lottory_status == 3) {
                $lot_ticket_status = $v['lottory_ticket_status'];
                if ($lot_ticket_status == 1) {
                    $lottory_status_name = '已中奖';
                } elseif ($lot_ticket_status == 2) {
                    $lottory_status_name = '未中奖';
                } else {
                    $lottory_status_name = '待开奖';
                }
            }
            $list[$k]['lot_status'] = $lottory_status_name;
            $list[$k]['ticket_comefrom'] = $ticket_comefrom;
        }
//        echo M()->getLastSql();
        $result = [
            'list'  => $list,
            'total' => $total,
        ];
        return $result;
    }

    /**
     * 根据中奖号码获得用户信息
     *
     * @param $lotId
     * @param $win_num
     *
     * @return mixed
     */
    public function get_win_detail($lotId, $win_num)
    {
        $condition['lot_id'] = $lotId;
        $condition['lottory_ticket_num'] = $win_num;
        return M('lottory_ticket', 'clcw_', 'DB_CLCW')->field('uid')->where($condition)->find();
    }

}
